package com.hcmus.arLocation;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcmus.armobile.R;
import com.hcmus.post2server.post2server;
import common.Store;

import Server.HandleServer;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Log;
import android.widget.Toast;
import global.*;
public class DentifierDataSource extends NetworkDataSource{
	//private static final String BASE_URL = "http://ws.geonames.org/findNearbyWikipediaJSON";
	private static SQLiteDatabase db;
	private static Bitmap icon = null;
	private static Resources rs = null;
	private static Context ct = null;
	public DentifierDataSource(Resources res, Context _ct) {        
	    if (res==null) throw new NullPointerException();
        rs = res;
        ct = _ct;
      //  createIcon(res);
    }

    public Bitmap createIcon(Resources res, int DrawableID) {
        if (res==null) throw new NullPointerException();
        Bitmap iconResult = null;
        iconResult = BitmapFactory.decodeResource(res, R.drawable.imgtest1);
        return iconResult;
    }

//	@Override
//	public String createRequestURL(double lat, double lon, double alt, float radius, String locale) {
//		return BASE_URL+
//        "?lat=" + lat +
//        "&lng=" + lon +
//        "&radius="+ radius +
//        "&maxRows=40" +
//        "&lang=" + locale;
//
//	}

	@Override
	public List<Marker> parse(JSONObject root) {
		if (root==null) return null;
		
		JSONObject jo = null;
		JSONArray dataArray = null;
    	List<Marker> markers=new ArrayList<Marker>();

		try {
			if(root.has("DentifierDataSource")) dataArray = root.getJSONArray("DentifierDataSource");
			if (dataArray == null) return markers;
				int top = Math.min(MAX, dataArray.length());
				for (int i = 0; i < top; i++) {					
					jo = dataArray.getJSONObject(i);
					Marker ma = processJSONObject(jo);
					if(ma!=null) markers.add(ma);
				}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return markers;
	}
	  
	
	 public static JSONObject LoadDataSourcePostNew(String lat , String lng , String distance){
			JSONArray jsonRoot = new JSONArray();
			 JSONObject result = null;
			
		    	ArrayList<Store> lstStore = new ArrayList<Store>();
		    	
		    	lstStore = HandleServer.GetListStoreNearPosition("10.3435553","106.342455","500");
		    	//lstStore = HandleServer.GetListStoreNearPosition(lat,lng,distance);
				
		    	try{
		    		
		    		
		    		String id = "id";
		    		String name="name";
		    		String AddressShopping = "AddressShopping";
		    		String PromotionShopping= "PromotionShopping";
		    		String LocationType = "1";
		    		String ShopChainName = "ShopChainName";
		    		String Longitude= "Longitude";
		    		String Latitude= "Latitude";
		    		String Altitude= "12.1313";
		    		String imgUrl = "1";
		    		String type="";
		    		
		    		for(int i = 0 ; i< lstStore.size() ; i++){
		    			Store s = lstStore.get(i);
		    			id = String.valueOf(s.getId());
		    			type = String.valueOf(s.getType());
		    			name = s.getName();
		    			Latitude = s.getLat();
		    			Longitude = s.getLng();
		    			Altitude = "5";//s.getAlt();
		    			imgUrl = "1";
		    			LocationType = String.valueOf(s.getType());			    			
		    			PromotionShopping = s.getName();
		    			AddressShopping = s.getAddress();
		    			ShopChainName = "Demo";			    			
		    			JSONObject jOb = new JSONObject();
						jOb.put("ID",id); 
						jOb.put("Title", name);
						jOb.put("AddressShopping", AddressShopping);
						jOb.put("PromotionShopping", PromotionShopping);
						jOb.put("LocationType", LocationType);
						jOb.put("ShopChainName", ShopChainName);
						jOb.put("Longitude", Double.parseDouble(Longitude));
						jOb.put("Latitude", Double.parseDouble(Latitude));
						jOb.put("Altitude", Double.parseDouble(Altitude));
						jOb.put("ImgUrl", Integer.parseInt(imgUrl));
						jsonRoot.put(jOb);							
		    		}		    		
		    		 result = new JSONObject();
				    	try {
							result.put("DentifierDataSource", jsonRoot);
						} catch (JSONException e) { 
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				   
		    	return result;
		    	
		    }catch(Exception e){
		    
		    }
			return result;
 	}
	 
	
	public List<Marker> parseNonNetwork(JSONObject root) {
		if (root==null) return null;
		
		JSONObject jo = null;
		JSONArray dataArray = null;
    	List<Marker> markers=new ArrayList<Marker>();

		try {
			if(root.has("DentifierDataSource")) dataArray = root.getJSONArray("DentifierDataSource");
			if (dataArray == null) return markers;
				int top = Math.min(MAX, dataArray.length());
				for (int i = 0; i < top; i++) {					
					jo = dataArray.getJSONObject(i);
					Marker ma = processJSONObject(jo);
					if(ma!=null) markers.add(ma);
				}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return markers;
	}
	
	private Marker processJSONObject(JSONObject jo) {
		if (jo==null) return null;
		
        Marker ma = null;
        if (	jo.has("Title") && 
        		jo.has("AddressShopping") &&
				jo.has("PromotionShopping") &&
				jo.has("LocationType") &&
				jo.has("ShopChainName") &&
        		jo.has("Latitude") && 
        		jo.has("Longitude") && 
        		jo.has("Altitude") &&
        		jo.has("ImgUrl")
        ) {
        	try {
        		ma = new IconMarker(
        				jo.getString("Title"),
        				jo.getString("AddressShopping"),
        				jo.getString("PromotionShopping"),
        				jo.getString("LocationType"),
        				jo.getString("ShopChainName"),
        				jo.getDouble("Latitude"),
        				jo.getDouble("Longitude"),
        				jo.getDouble("Altitude"),
        				Color.WHITE,
        				createIcon(rs,jo.getInt("ImgUrl")));
        	} catch (JSONException e) {
        		e.printStackTrace();
        	}
        }
        return ma;
	}

	@Override
	public String createRequestURL(double lat, double lon, double alt,
			float radius, String locale) {
		// TODO Auto-generated method stub
		return null;
	}
	
	 public static JSONObject LoadDataSource(String sql){
		 
		 JSONArray jsonRoot = new JSONArray();
		 JSONObject result = null;
	    	try{
		    		//String uriPath = "android.resource://"+ct.getPackageName()+"/datasource";
		    		//Uri uri = Uri.parse(uriPath);	    		
		    		String stPathToDB = android.os.Environment.getExternalStorageDirectory().toString()+"/database/DataSource.db";
		    		//String stPathToDB = "/storage/extSdCard/database/DataSource.db";
		    		//Toast.makeText(ct,"have in here........................", 4).show();
					 db = SQLiteDatabase.openDatabase(stPathToDB, null, SQLiteDatabase.OPEN_READONLY);
					
					/* String sql = "";
						// drop table
						sql = "drop table if exists LocationInformation";
						db.execSQL(sql);
	
						// create table
						sql = "create table LocationInformation(\n"
								+ "ID integer PRIMARY KEY autoincrement,\n"
								+ "Name text,\n" +"Longitude text,\n" +"Latitude text,\n" +"Altitude text,\n" + " imgUrl\n" + ");";
						db.execSQL(sql);
	
						// insert data
						sql = "insert into LocationInformation(Name,Longitude,Latitude,Altitude,imgUrl) values('name','long','lat','altitude','img');";
						db.execSQL(sql);
						
					*/
					 
					//String sqlMe = "SELECT * FROM LocationInformation li LEFT JOIN LocationType lt ON(li.IDLocationType = lt.IDLocationType) ORDER BY li.ID ASC";
					String sqlMe = sql; 
					Cursor cur = db.rawQuery(sqlMe,null);					
					int idIdentify = cur.getColumnIndex("ID");
					int idName = cur.getColumnIndex("Name");
					int idAddressShopping = cur.getColumnIndex("AddressInfo");
					int idpromotionShopping = cur.getColumnIndex("PromoteInfo");
					int idLocationType = cur.getColumnIndex("IDLocationShoppingType");
					int idShopChainName = cur.getColumnIndex("ShopChainName");
					int idLongitude = cur.getColumnIndex("Longitude");
					int idLatitude = cur.getColumnIndex("Latitude");
					int idAltitude = cur.getColumnIndex("Altitude");
					int idImgUrl = cur.getColumnIndex("imgUrl");
					while (cur.moveToNext()) {
						String id = Integer.toString(cur.getInt(idIdentify));
						String Name = cur.getString(idName);
						String AddressShopping = cur.getString(idAddressShopping);
						String PromotionShopping = cur.getString(idpromotionShopping);
						String LocationType = Integer.toString(cur.getInt(idLocationType));
						String ShopChainName = cur.getString(idShopChainName);
						String Longitude = cur.getString(idLongitude);
						String Latitude = cur.getString(idLatitude);
						String Altitude = cur.getString(idAltitude);
						String imgUrl = cur.getString(idImgUrl); 	 										
						JSONObject jOb = new JSONObject();
						jOb.put("ID", Integer.parseInt(id));
						jOb.put("Title", Name);
						jOb.put("AddressShopping", AddressShopping);
						jOb.put("PromotionShopping", PromotionShopping);
						jOb.put("LocationType", LocationType);
						jOb.put("ShopChainName", ShopChainName);
						jOb.put("Longitude", Double.parseDouble(Longitude));
						jOb.put("Latitude", Double.parseDouble(Latitude));
						jOb.put("Altitude", Double.parseDouble(Altitude));
						jOb.put("ImgUrl", Integer.parseInt(imgUrl));
						jsonRoot.put(jOb);
					}
					db.close();
					result = new JSONObject();
			    	try {
						result.put("DentifierDataSource", jsonRoot);
					} catch (JSONException e) { 
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (Exception e) {	
					e.printStackTrace();
					db.close();
					
				}
	    	
	    	return result;
	    	
	    }
	    public static String formatString(String value){
	    	String result = "";
	    	result = value.toLowerCase();
	    	result = result.replace("-", "_");
	    	result = result.replace(" ", "_");
	    	result = result.replace("'","_");
	    	return result;
	    }
	    
	    
	    public static JSONObject LoadDataSourcePost(String lat , String lng , String distance){
			
	    	if(config.config.getDataServer_v1 == true){
	    		JSONArray jsonRoot = new JSONArray();
				 JSONObject result = null;
				
			    	
			    	try{
			    		
			    		final Map<String, String> params = new HashMap<String, String>();
				        params.put("type_post", "get_data_by_position");
			    		params.put("message", "message");
			    		params.put("regId", global.curUser.getRegId());
				        params.put("lat", lat);
				        params.put("lng", lng);
				        params.put("dis", distance);
				        
			    		
			    		String result_post = post2server.postRecive(params);		    				            
				        String me = "congtt%%nguyenvana%%300434%%congtt";
				        String[]mearr = me.split("%%");
				        
			    		String id = "id";
			    		String name="name";
			    		String AddressShopping = "AddressShopping";
			    		String PromotionShopping= "PromotionShopping";
			    		String LocationType = "1";
			    		String ShopChainName = "ShopChainName";
			    		String Longitude= "Longitude";
			    		String Latitude= "Latitude";
			    		String Altitude= "12.1313";
			    		String imgUrl = "1";
			    		String type="";
			    		
			    		String str = "";
			    		String char_p = "@store@";
			    		String  char1_p = "@s@";
			    		
			    		String[] lst = result_post.split(char_p);
			    		
			    		for(int i = 0 ; i< lst.length ; i++){
			    			String temp = lst[i];
			    			
			    			String[] arr = temp.split(char1_p); 
			    			
			    			id=arr[0];
			    			type = arr[2];
			    			name = arr[1];		    			
			    			Latitude = arr[6];
			    			Longitude = arr[5];
			    			Altitude = "5";
			    			imgUrl = "1";
			    			LocationType = arr[2];
			    			PromotionShopping = arr[7];
			    			AddressShopping = arr[11]+arr[10]+arr[9];
			    			ShopChainName = "Demo";
			    		
			    			
			    			
			    			JSONObject jOb = new JSONObject();
							jOb.put("ID",id); 
							jOb.put("Title", name);
							jOb.put("AddressShopping", AddressShopping);
							jOb.put("PromotionShopping", PromotionShopping);
							jOb.put("LocationType", LocationType);
							jOb.put("ShopChainName", ShopChainName);
							jOb.put("Longitude", Double.parseDouble(Longitude));
							jOb.put("Latitude", Double.parseDouble(Latitude));
							jOb.put("Altitude", Double.parseDouble(Altitude));
							jOb.put("ImgUrl", Integer.parseInt(imgUrl));
							jsonRoot.put(jOb);
							
			    		}		    		
			    		 result = new JSONObject();
					    	try {
								result.put("DentifierDataSource", jsonRoot);
							} catch (JSONException e) { 
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					   
			    	return result;
			    	
			    }catch(Exception e){
			    
			    }
				return result;
	    	}else{
	    		
	    		JSONArray jsonRoot = new JSONArray();
				 JSONObject result = null;
				
			    	
			    	try{
			    		
			    		final Map<String, String> params = new HashMap<String, String>();
				        params.put("message", "message");
				        params.put("lat", lat);
				        params.put("long", lng);
				        params.put("dis", distance);
				        
			    		
			    		String result_post = post2server.postRecive(params);		    				            
				        String me = "congtt%%nguyenvana%%300434%%congtt";
				        String[]mearr = me.split("%%");
				        
			    		String id = "id";
			    		String name="name";
			    		String AddressShopping = "AddressShopping";
			    		String PromotionShopping= "PromotionShopping";
			    		String LocationType = "1";
			    		String ShopChainName = "ShopChainName";
			    		String Longitude= "Longitude";
			    		String Latitude= "Latitude";
			    		String Altitude= "12.1313";
			    		String imgUrl = "1";
			    		
			    		
			    		String str = "";
			    		String char_p = "#@#";
			    		String  char1_p = "(%%)";
			    		
			    		String[] lst = result_post.split(char_p);
			    		
			    		for(int i = 0 ; i< lst.length ; i++){
			    			String temp = lst[i];
			    			
			    			String[] arr = temp.split(char1_p); 
			    			
			    			id=arr[0];
			    			
			    			name = arr[1];		    			
			    			Latitude = arr[2];
			    			Longitude = arr[3];
			    			Altitude = arr[4];
			    			imgUrl = arr[5];
			    			LocationType = arr[6];
			    			PromotionShopping = arr[7];
			    			AddressShopping = arr[8];
			    			ShopChainName = arr[9];
			    		
			    			
			    			
			    			JSONObject jOb = new JSONObject();
							jOb.put("ID",id); 
							jOb.put("Title", name);
							jOb.put("AddressShopping", AddressShopping);
							jOb.put("PromotionShopping", PromotionShopping);
							jOb.put("LocationType", LocationType);
							jOb.put("ShopChainName", ShopChainName);
							jOb.put("Longitude", Double.parseDouble(Longitude));
							jOb.put("Latitude", Double.parseDouble(Latitude));
							jOb.put("Altitude", Double.parseDouble(Altitude));
							jOb.put("ImgUrl", Integer.parseInt(imgUrl));
							jsonRoot.put(jOb);
							
			    		}		    		
			    		 result = new JSONObject();
					    	try {
								result.put("DentifierDataSource", jsonRoot);
							} catch (JSONException e) { 
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
					   
			    	return result;
			    	
			    }catch(Exception e){
			    
			    }
				return result;
				
	    	}
	    	
			 
	    }
	    
	    public static JSONObject LoadDataSourcePost_json(String lat, String lng,
				String distance) {

			JSONArray jsonRoot = new JSONArray();
			JSONObject result = null;

			try {

				final Map<String, String> params = new HashMap<String, String>();
				params.put("message", "message");
				params.put("lat", lat);
				params.put("long", lng);
				params.put("dis", distance);

				String result_post = post2server.postRecive(params);

				JSONObject json = null;
				try {
					json = new JSONObject(result_post);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				ArrayList<String> list = new ArrayList<String>();
				JSONArray jsonArray = (JSONArray) json.getJSONArray("");
				if (jsonArray != null) {
					for (int i = 0; i < jsonArray.length(); i++) {
						list.add(jsonArray.get(i).toString());
					}
				}

				String id = "id";
				String name = "name";
				String AddressShopping = "AddressShopping";
				String PromotionShopping = "PromotionShopping";
				String LocationType = "1";
				String ShopChainName = "ShopChainName";
				String Longitude = "Longitude";
				String Latitude = "Latitude";
				String Altitude = "Altitude";
				String imgUrl = "imgUrl";

				result = new JSONObject();
				try {
					result.put("DentifierDataSource", jsonRoot);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (Exception e) {
				
			}
			return result;

		}
	    
	    
}
